<template>
  <div class="member-management-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <h1 class="page-title">成员管理</h1>
      <div class="page-description">{{ spaceInfo.spaceName }} 团队空间的成员列表</div>
      <el-button
        type="primary"
        class="add-member-btn"
        @click="showAddMemberDialog = true"
        :disabled="!hasManagePermission"
      >
        <i class="el-icon-plus"></i> 添加成员
      </el-button>
    </div>

    <!-- 成员列表表格 -->
    <div class="member-table-container">
      <el-table :data="memberList" border stripe style="width: 100%" :loading="loading">
        <el-table-column prop="user.userName" label="成员名称" width="180">
          <template #default="scope">
            <div class="user-info">
              <el-avatar :src="scope.row.user.userAvatar" class="user-avatar">
                {{ scope.row.user.userName.charAt(0) }}
              </el-avatar>
              <span class="user-name">{{ scope.row.user.userName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="user.email" label="邮箱" width="220"></el-table-column>
        <el-table-column prop="spaceRole" label="角色" width="140">
          <template #default="scope">
            <el-select
              v-model="scope.row.spaceRole"
              size="small"
              @change="handleRoleChange(scope.row)"
              :disabled="!canModifyRole(scope.row)"
            >
              <el-option label="查看者" value="viewer"></el-option>
              <el-option label="编辑者" value="editor"></el-option>
              <el-option label="管理员" value="admin"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="加入时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button
              v-if="canRemoveMember(scope.row)"
              type="text"
              size="small"
              class="text-danger"
              @click="handleRemoveMember(scope.row)"
            >
              移除
            </el-button>
            <span v-else class="text-disabled">无法移除</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <div v-if="memberList.length === 0 && !loading" class="empty-state">
        <div class="empty-icon">
          <i class="el-icon-users"></i>
        </div>
        <h3 class="empty-title">暂无成员</h3>
        <p class="empty-desc">添加成员到团队空间，共同协作管理素材</p>
        <el-button
          type="primary"
          @click="showAddMemberDialog = true"
          class="empty-action"
          :disabled="!hasManagePermission"
        >
          <i class="el-icon-plus"></i> 添加成员
        </el-button>
      </div>
    </div>

    <!-- 添加成员对话框 -->
    <el-dialog
      title="添加成员到团队空间"
      v-model="showAddMemberDialog"
      width="500px"
      @close="resetAddForm"
    >
      <el-form
        :model="addMemberForm"
        ref="addMemberFormRef"
        :rules="addMemberRules"
        label-width="100px"
        class="add-member-form"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input
            v-model="addMemberForm.userId"
            placeholder="请输入要添加的用户ID"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="成员角色" prop="spaceRole">
          <el-select v-model="addMemberForm.spaceRole" placeholder="请选择成员角色">
            <el-option label="查看者" value="viewer"></el-option>
            <el-option label="编辑者" value="editor"></el-option>
            <el-option label="管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邀请信息" prop="inviteMessage">
          <el-input
            v-model="addMemberForm.inviteMessage"
            type="textarea"
            rows="3"
            placeholder="可选，添加邀请成员的理由或说明"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddMemberDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAddMember">确定添加</el-button>
      </template>
    </el-dialog>

    <!-- 移除成员确认对话框 -->
    <el-dialog
      title="确认移除成员"
      v-model="showRemoveConfirmDialog"
      width="400px"
      :show-close="false"
    >
      <div class="remove-confirm-content">
        <p>
          您确定要将 <span class="text-highlight">{{ currentMember.user.userName }}</span> 移出
          {{ spaceInfo.spaceName }} 团队空间吗？
        </p>
        <p class="text-warning">移除后，该成员将无法访问此空间的内容。</p>
      </div>
      <template #footer>
        <el-button @click="showRemoveConfirmDialog = false">取消</el-button>
        <el-button type="danger" @click="confirmRemoveMember">确认移除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import {
  addSpaceUserAPI,
  deleteSpaceUserAPI,
  listSpaceUserAPI,
  editSpaceUserAPI,
} from '@/api/spaceUserAPI'
import { useUserStore } from '@/stores/user'

// 路由和存储
const route = useRoute()
const userStore = useUserStore()

// 空间信息
const spaceId = ref(route.query.spaceId || null)
const spaceInfo = ref({
  spaceName: '团队空间',
})

// 成员列表数据
const memberList = ref([])
const loading = ref(false)

// 对话框状态
const showAddMemberDialog = ref(false)
const showRemoveConfirmDialog = ref(false)
const currentMember = ref(null)

// 添加成员表单
const addMemberForm = reactive({
  spaceId: spaceId.value,
  userId: null,
  spaceRole: 'viewer',
  inviteMessage: '',
})

// 表单验证规则
const addMemberRules = reactive({
  userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  spaceRole: [{ required: true, message: '请选择成员角色', trigger: 'change' }],
})

// 表单引用
const addMemberFormRef = ref(null)

// 当前用户是否有管理权限
const hasManagePermission = computed(() => {
  console.log(memberList.value)
  console.log(userStore.userInfo.id)

  const currentUser = memberList.value.find((m) => m.user.id === userStore.userInfo.id)
  console.log('currentUser', currentUser)

  return currentUser && currentUser.spaceRole === 'admin'
})

// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm') : ''
}

// 检查当前用户是否可以修改指定成员的角色
const canModifyRole = (member) => {
  // 获取当前登录用户在该空间的角色
  const currentUser = memberList.value.find((m) => m.user.id === userStore.userInfo.id)

  // 只有管理员可以修改角色
  if (!currentUser || currentUser.spaceRole !== 'admin') {
    return false
  }

  // 不能修改自己的角色
  if (member.user.id === userStore.userInfo.id) {
    return false
  }

  // 管理员不能被其他管理员修改
  if (member.spaceRole === 'admin') {
    return false
  }

  return true
}

// 检查是否可以移除成员
const canRemoveMember = (member) => {
  // 获取当前登录用户在该空间的角色
  const currentUser = memberList.value.find((m) => m.user.id === userStore.userInfo.id)
  // 只有管理员可以移除成员
  if (!currentUser || currentUser.spaceRole !== 'admin') {
    return false
  }

  // 不能移除自己
  if (member.user.id === userStore.userInfo.id) {
    return false
  }

  // 管理员不能被移除
  if (member.spaceRole === 'admin') {
    return false
  }

  return true
}

// 获取成员列表
const fetchMemberList = async () => {
  if (!spaceId.value) {
    ElMessage.error('空间ID不存在')
    return
  }

  loading.value = true
  try {
    const res = await listSpaceUserAPI({ spaceId: spaceId.value })
    memberList.value = res.data || []
    // 获取空间信息（从第一个成员的空间信息中获取）
    if (memberList.value.length > 0 && memberList.value[0].space) {
      spaceInfo.value = memberList.value[0].space
    }
  } catch (error) {
    console.error('获取成员列表失败:', error)
    ElMessage.error('获取成员列表失败')
  } finally {
    loading.value = false
  }
}

// 处理添加成员
const handleAddMember = async () => {
  // 表单验证
  if (!addMemberFormRef.value) return
  await addMemberFormRef.value.validate().catch(() => {
    return Promise.reject(new Error('表单验证失败'))
  })

  // 设置空间ID
  addMemberForm.spaceId = spaceId.value

  try {
    const res = await addSpaceUserAPI(addMemberForm)
    if (res.code === 200) {
      ElMessage.success('成员添加成功')
      showAddMemberDialog.value = false
      resetAddForm()
      fetchMemberList()
    } else {
      ElMessage.error(res.message || '添加成员失败')
    }
  } catch (error) {
    console.error('添加成员失败:', error)
    ElMessage.error('添加成员失败')
  }
}

// 处理角色变更
const handleRoleChange = async (member) => {
  if (!member.id) {
    ElMessage.error('成员ID不存在')
    return
  }

  try {
    const res = await editSpaceUserAPI({
      id: member.id,
      spaceRole: member.spaceRole,
    })
    if (res.code === 200) {
      ElMessage.success('角色更新成功')
      fetchMemberList()
    } else {
      ElMessage.error(res.message || '更新角色失败')
      // 失败时回滚显示
      fetchMemberList()
    }
  } catch (error) {
    console.error('更新角色失败:', error)
    ElMessage.error('更新角色失败')
    // 失败时回滚显示
    fetchMemberList()
  }
}

// 处理移除成员
const handleRemoveMember = (member) => {
  currentMember.value = member
  showRemoveConfirmDialog.value = true
}

// 确认移除成员
const confirmRemoveMember = async () => {
  if (!currentMember.value || !currentMember.value.id) {
    ElMessage.error('成员信息不正确')
    return
  }

  try {
    const res = await deleteSpaceUserAPI(currentMember.value.id)
    if (res.code === 200) {
      ElMessage.success('成员已移除')
      showRemoveConfirmDialog.value = false
      fetchMemberList()
      currentMember.value = null
    } else {
      ElMessage.error(res.message || '移除成员失败')
    }
  } catch (error) {
    console.error('移除成员失败:', error)
    ElMessage.error('移除成员失败')
  }
}

// 重置添加成员表单
const resetAddForm = () => {
  if (addMemberFormRef.value) {
    addMemberFormRef.value.resetFields()
  }
  addMemberForm.userId = null
  addMemberForm.spaceRole = 'viewer'
  addMemberForm.inviteMessage = ''
}

// 页面加载时获取成员列表
onMounted(() => {
  // 确保用户信息已加载
  if (userStore.userInfo.id) {
    fetchMemberList()
  } else {
    // 如果用户信息未加载，监听用户信息变化
    const unwatch = userStore.$watch('userInfo.id', (newVal) => {
      if (newVal) {
        fetchMemberList()
        unwatch() // 只执行一次
      }
    })
  }
})
</script>

<style scoped>
.member-management-container {
  padding: 24px;
  background-color: #f8fafc;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.page-description {
  color: #64748b;
  margin: 0;
  flex: 1;
  min-width: 200px;
}

.add-member-btn {
  background-color: #2563eb;
  border-color: #2563eb;
  white-space: nowrap;
}

.add-member-btn:hover {
  background-color: #1d4ed8;
  border-color: #1d4ed8;
}

/* 成员表格容器 */
.member-table-container {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  padding: 16px;
}

/* 用户信息显示 */
.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-avatar {
  width: 36px;
  height: 36px;
  font-size: 16px;
}

.user-name {
  font-weight: 500;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #64748b;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  color: #94a3b8;
}

.empty-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #334155;
}

.empty-desc {
  max-width: 400px;
  margin: 0 auto 24px;
  line-height: 1.6;
}

/* 添加成员表单 */
.add-member-form {
  margin-top: 16px;
}

/* 移除确认对话框 */
.remove-confirm-content {
  padding: 10px 0;
}

.text-highlight {
  color: #2563eb;
  font-weight: 500;
}

.text-warning {
  color: #f59e0b;
  margin-top: 10px;
  font-size: 14px;
}

.text-danger {
  color: #ef4444;
}

.text-disabled {
  color: #94a3b8;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .add-member-btn {
    width: 100%;
  }
}
</style>
